package com.mdinic.blogovi.front.page.person.picture;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.resource.DynamicImageResource;
import org.apache.wicket.request.resource.IResource;

import com.mdinic.blogovi.front.common.AbstractBasePage;
import com.mdinic.blogovi.front.common.coppableimage.CroppableImage;

/**
 * Class that represents why join page.
 * 
 * @author mdinic
 */
public class ChopPhotoPage extends AbstractBasePage {
    // TODO make this work
    private static final long serialVersionUID = 1L;

    private final Rectangle cropArea = new Rectangle();

    private static BufferedImage bufferedImage;

    /**
     * Constructor.
     */
    public ChopPhotoPage() {
        super(true);

        try {
            bufferedImage = ImageIO.read(ChopPhotoPage.class.getResource("mdinic.jpg"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        final Label label = new Label("info", new AbstractReadOnlyModel<Object>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Object getObject() {
                return "Size: " + cropArea.width + "&times;" + cropArea.height + " px";
            }
        });
        label.setEscapeModelStrings(false);
        add(label);
        label.setOutputMarkupId(true);

        IResource resource = new DynamicImageResource("jpeg") {

            private static final long serialVersionUID = 7749490302987174338L;

            @Override
            protected byte[] getImageData(Attributes attributes) {
                return toImageData(bufferedImage);
            }
        };

        CroppableImage croppable = new CroppableImage("image", new PropertyModel<Rectangle>(this, "cropArea"), resource) {

            private static final long serialVersionUID = 1L;

            @Override
            public void onCropAreaUpdate(AjaxRequestTarget target) {
                target.add(label);
            }
        };
        add(croppable);
        // croppable.setMinHeight(32);
        // croppable.setMinWidth(32);

        add(new Link<Void>("crop") {
            private static final long serialVersionUID = -3100172837357475551L;

            @Override
            public void onClick() {
                if (cropArea.width > 0 && cropArea.height > 0) {
                    bufferedImage = bufferedImage.getSubimage(cropArea.x, cropArea.y, cropArea.width, cropArea.height);
                }
            }
        });
    }

}
